package com.example.martian.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.martian.mapper.CustodyMapper;
import com.example.martian.mapper.MartianOrePoolMapper;
import com.example.martian.pojo.YzcmMillOrder;
import com.example.martian.pojo.YzcmTopup;
import com.example.martian.service.MartianOrePoolService;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CustodyUtils {

    @Autowired
    private CustodyMapper custodyMapper;

    @Autowired
    private MartianOrePoolMapper martianOrePoolMapper;

    @Autowired
    private Web3JConfig web3JConfig;

    @Autowired
    private MartianOrePoolService martianOrePoolService;

    public void addTopUp(String address,String created_time,String coin,String value,
                         String side,String status,String fromAddress,String toAddress,String uuid,Integer type){
        YzcmTopup yzcmTopup = new YzcmTopup();
        yzcmTopup.setCmcAddress(address);
        yzcmTopup.setCmcFromAddressKey(fromAddress);
        yzcmTopup.setCmcToAddressKey(toAddress);
        yzcmTopup.setCmcStatus(status);
        yzcmTopup.setCmcSide(side);
        yzcmTopup.setCmcCoin(coin);
        yzcmTopup.setCmcValue(value);
        yzcmTopup.setCmcCreateTime(created_time);
        yzcmTopup.setCmcUuid(uuid);
        yzcmTopup.setCmcType(type);
        custodyMapper.insertTopUpRecord(yzcmTopup);
    }

    public void addMillOrder(String address,String created_time,String logo,BigDecimal value,Integer zt,Integer productId,
                         Integer number,Integer payment_method,String uuid,Integer type,String productName,Integer userId){
        YzcmMillOrder yzcmMillOrder = new YzcmMillOrder();
        yzcmMillOrder.setCmcAddress(address);
        yzcmMillOrder.setCmcCreateTime(created_time);
        yzcmMillOrder.setCmcOrderType(type);
        yzcmMillOrder.setCmcLogo(logo);
        yzcmMillOrder.setCmcNumber(number);
        yzcmMillOrder.setCmcPaymentMethod(payment_method);
        yzcmMillOrder.setCmcZt(zt);
        yzcmMillOrder.setCmcPaymentMoney(value);
        yzcmMillOrder.setCmcOrderNumber(uuid);
        yzcmMillOrder.setCmcProductName(productName);
        yzcmMillOrder.setCmcProductId(productId);
        yzcmMillOrder.setCmcAddressId(userId);
        martianOrePoolMapper.insertOrder(yzcmMillOrder);
    }

    public boolean getRecordList(String uuid,String address) throws Exception {
        Integer type = 0;
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");
        JSONObject withdrawInfoByRequestId = Custody.withdraw_info_by_request_id(uuid);
        Boolean success = withdrawInfoByRequestId.getBoolean("success");
        BigInteger error_code = withdrawInfoByRequestId.getBigInteger("error_code");
        if (!success){
            return false;
        }
        JSONObject result = (JSONObject) withdrawInfoByRequestId.get("result");
            //交易时间
        String create_time = dateFormat.format(result.get("created_time"));
        String coin = result.get("coin").toString();//交易币种
        if (coin.equals("TETH")){
            coin = "ETH";
        }
        String value =  new BigDecimal(result.getBigDecimal("amount").//交易金额
                divide(BigDecimal.valueOf(1e18), 10, BigDecimal.ROUND_HALF_EVEN).toPlainString()).toString();
        String side = result.get("side").toString();//交易规则  deposit 充值 / withdraw 提现
        String status = result.get("status").toString();//状态  是否成功
        String toAddress = result.get("address").toString();//充值地址
        String fromAddress = result.get("source_address").toString() ;//源地址
        addTopUp(address,create_time,coin,value,side,status,fromAddress,toAddress,uuid,type);
        return true;
    }

    //划转
    public Map<String,Object> getTransferList(String uuid,String address) throws Exception {
        Map<String,Object> param = new HashMap<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject withdrawInfoByRequestId = Custody.withdraw_info_by_request_id(uuid);
        Boolean success = withdrawInfoByRequestId.getBoolean("success");
        BigInteger error_code = withdrawInfoByRequestId.getBigInteger("error_code");
        if (!success){
            param.put("success","false");
            param.put("error_code",error_code);
            return param;
        }
        JSONArray jsonArray = withdrawInfoByRequestId.getJSONArray("result");
        String side = "";

        for (int flg = 0;flg<jsonArray.size();flg++){
            JSONObject resultObj = (JSONObject) jsonArray.get(flg);
            //交易时间
            String create_time = dateFormat.format(resultObj.get("created_time"));
            String coin = resultObj.get("coin").toString();//交易币种
            if (coin.equals("TETH")){
                coin = "ETH";
            }
            String value =  new BigDecimal(resultObj.getBigDecimal("amount").//交易金额
                    divide(BigDecimal.valueOf(1e18), 10, BigDecimal.ROUND_HALF_EVEN).toPlainString()).toString();
            side = resultObj.get("side").toString();//交易规则  deposit 充值 / withdraw 提现
            String status = resultObj.get("status").toString();//状态  是否成功
            String toAddress = resultObj.get("address").toString();//充值地址
            String fromAddress = resultObj.get("source_address").toString() ;//源地址
            param.put("uuid",uuid);//交易唯一ID
            param.put("created_time",create_time);//交易时间
            param.put("coin",coin);//交易币种
            param.put("value",value);//交易金额
            param.put("side",side);//交易规则  deposit 充值 / withdraw 提现
            param.put("status",status);//状态  是否成功
            param.put("toAddress",toAddress);//充值地址
            param.put("fromAddress",fromAddress);//源地址
            param.put("address",address);
            if (coin.equals("ETH_USDT")){
            }
        }
        return param;
    }


    @Transactional
    public JSONArray getMill(Integer goodsType,Integer typeMill) throws ParseException {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = null;
        List<Map<String, Object>> mapList = martianOrePoolMapper.selectMillAll(goodsType,typeMill);
        if (goodsType == 1){
            for (Map<String,Object> map : mapList){
                jsonObject = new JSONObject();
                if (map.get("cmc_subarea").equals("BTC")){
                    Object btcEarningsByDay = web3JConfig.getBtcEarningsByDay("BTC");
                    //每TH/S  * 算力T = 币种单日收益
                    BigDecimal multiplyHashrateBtc = new BigDecimal(btcEarningsByDay.toString()).
                            multiply(new BigDecimal(map.get("hashrate").toString()));
                    jsonObject.put("production",multiplyHashrateBtc);
                }
                if (map.get("cmc_subarea").equals("ETH")) {
                    Object ethEarningsByDay = martianOrePoolService.getEthEarningsByDay("ETH");
                    //每TH/S  * 算力T = 币种单日收益
                    BigDecimal multiplyHashrateEth = new BigDecimal(ethEarningsByDay.toString()).
                            multiply(new BigDecimal(map.get("hashrate").toString()));
                    jsonObject.put("production",multiplyHashrateEth);
                }
                jsonObject.put("image",map.get("image"));
                jsonObject.put("hashrate",map.get("hashrate"));
                jsonObject.put("power_diss",map.get("power_diss"));
                jsonObject.put("electric_charge",map.get("electric_charge"));
                jsonObject.put("mining_time",map.get("mining_time"));
                jsonObject.put("end_time",map.get("end_time"));
                jsonObject.put("name",map.get("name"));
//                jsonObject.put("production",map.get("cloud_day"));//计算得出  数据库还未有字段
                jsonObject.put("stock",map.get("stock"));
                jsonObject.put("earnings ",map.get("static_yield"));//计算得出
                jsonObject.put("administrative_fee",map.get("administrative_fee"));
                jsonObject.put("mill_cost",map.get("mill_cost"));
//                jsonObject.put("backTo",map.get("static_return_days"));//计算得出
                jsonObject.put("static","0.05");
                jsonObject.put("description",map.get("description"));
                jsonObject.put("productId",map.get("cmc_id"));
                jsonObject.put("cloud_hashrate",map.get("cloud_hashrate"));
                jsonObject.put("activity_price",map.get("activity_price"));
                jsonArray.add(jsonObject);
            }
        }
        if (goodsType == 2){
            for (Map<String,Object> map : mapList){
                jsonObject = new JSONObject();
                if (map.get("cmc_subarea").equals("BTC")){
                    Object btcEarningsByDay = web3JConfig.getBtcEarningsByDay("BTC");
                    //每TH/S  * 算力T = 币种单日收益
                    BigDecimal multiplyHashrateBtc = new BigDecimal(btcEarningsByDay.toString()).
                            multiply(new BigDecimal(map.get("hashrate").toString()));
                    jsonObject.put("production",multiplyHashrateBtc);
                }
                if (map.get("cmc_subarea").equals("ETH")) {
                    Object ethEarningsByDay = martianOrePoolService.getEthEarningsByDay("ETH");
                    //每TH/S  * 算力T = 币种单日收益
                    BigDecimal multiplyHashrateEth = new BigDecimal(ethEarningsByDay.toString()).
                            multiply(new BigDecimal(map.get("hashrate").toString()));
                    jsonObject.put("production",multiplyHashrateEth);
                }
                jsonObject.put("image",map.get("image"));
                jsonObject.put("period",map.get("period"));
                jsonObject.put("buynumber",map.get("buynumber"));
                jsonObject.put("mining_time",map.get("mining_time"));
                jsonObject.put("end_time",map.get("end_time"));
                jsonObject.put("name",map.get("name"));
//                jsonObject.put("production",map.get("cloud_day"));//计算得出  数据库还未有字段
                jsonObject.put("stock",map.get("stock"));
                jsonObject.put("earnings ",map.get("static_yield"));
                jsonObject.put("administrative_fee",map.get("administrative_fee"));
                jsonObject.put("mill_cost",map.get("mill_cost"));
                jsonObject.put("unitprice",map.get("unit_tprice"));
                jsonObject.put("description",map.get("description"));
                jsonObject.put("productId",map.get("cmc_id"));
                jsonObject.put("activity_price",map.get("activity_price"));
                System.out.println(jsonObject);
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray;
    }
}
